<?php
/**
 * @copyright 启才通-教培系统.
 * @author LiChun 2562272167@qq.com
 * @url http://www.qicaitong.net
 */

namespace app\home\controller;


use app\common\model\Area;
use app\common\model\CourseOutline;
use app\common\model\CourseVideo;
use app\common\model\Curr;
use think\Controller;
use think\Cookie;
use think\Db;
use think\Request;
use think\Session;
use app\common\model\User as UserModel;
use app\common\model\UserTest;

class Users extends Controller
{
    /**
     * 用户登录界面及登录功能
     */
    public function login()
    {
        // get请求跳转到登录页面
        Session::set('user', null);
        if (Request::instance()->isGet()) {
            if (Session::get('user')['user_id']) {
                return redirect('/users/login'); // 用户中心
            } else {
                return view('index/login');
            }
        }

        // post请求进行登录判断等操作
        if (Request::instance()->isPost()) {
            $data = Request::instance()->post();
            $username = $data['login_username_new'];
            $password = md5($data['login_password']);
            $data['still_login'] = '';
            $user = UserModel::where('name', $username)->where('password', $password)->find();
            if ($user) {
                $user_details = UserTest::where('user_id', $user->id)->find();
                $session_user['user_id'] = $user->id;
                $session_user['name'] = $user->name;
                $session_user['nc'] = $user_details->real_name;
                $type = $user->account_type;
                Session::set('user', $session_user);
                Session::set('type', $type);
                $usertets = Db::table('bk_user_test')
                    ->where('user_id', $session_user['user_id'])
                    ->find();
                $area['province'] = Db::table('bk_area')->where('id', $usertets['province'])->value('name');
                $area['city'] = Db::table('bk_area')->where('id', $usertets['city'])->value('name');
                Session::set('area', $area);
                if (array_key_exists('still_login', $data)) {
                    $user->token = $data['__token__'];
                    $user->still_login = time() + 129600;
                    Cookie::set('still_login', $data['__token__']);
                } else {
                    $user->token = '';
                    $user->still_login = '';
                }

                $user->last_login = date('Y-m-d H:i:s', time());
                $user->save();
                return (['code' => 1, 'msg' => '登录成功']);

            } else {
                return (['code' => 0, 'msg' => '用户名或密码错误']);
            }
        }

    }

    /**
     * 个人中心
     */
    public function user_center()
    {
        // 登录状态
        if (!Session::get('user')['user_id']) {
            $this->redirect('/users/login');
            $this->error('您尚未登录系统', url('/users/login'));
        }

        // 查看用户购买课程的订单
        $products = db('order')->alias('a')->join('product b', 'a.product_id=b.id')->where('b.shopsxj', '=', '1')->where('a.user_id', Session::get('user')['user_id'])->where('pay_status', 1)->select();
        $examLists = array();
        $starer = array();
        if ($products) {
            foreach ($products as $product) {
                $adsaf = $this->category($product['product_id']);
                if ($adsaf['studyPro']["pro"] == $adsaf['studyPro']['sTime']) {
                    $sdgjk['code'] = '已完成';
                    $sdgjk['bfb'] = '100%';
                    $sdgjk['bfbs'] = 100;
                } else if ($adsaf['studyPro']["pro"] < $adsaf['studyPro']['sTime']) {
                    $sdgjk['code'] = '未完成';
                    $num = $adsaf['studyPro']['pro'] / $adsaf['studyPro']['sTime'];
                    $str = round($num * 100);
                    $sdgjk['bfbs'] = $str;
                    $sdgjk['bfb'] = $str . '%';
                }
                $sdgjk['title'] = $product['title'];
                $sf = db('curl')->where('curlid', $product['classes'])->find();
                $sdgjk['ry'] = $sf['curlname'];
                $daf = db('curr')->where('id', $product['currid'])->find();
                $sdgjk['ly'] = $daf['currname'] . '领域';
                $timesd = db('buylist')->where('uid', $product['user_id'])->where('product_id', $product['product_id'])->find();
                if ($timesd['buytime'] && $timesd['expTime']) {
                    $sdgjk['timeks'] = date('Y-m-d', $timesd['buytime']) . '-' . date('Y-m-d', $timesd['expTime']);
                } else {
                    $sdgjk['timeks'] = '已购买视频，请先前往观看课程';
                }
                $sdgjk['product_id'] = $product['product_id'];
                $sdgjk['thumb'] = $product['thumb'];
                $starer[] = $sdgjk;
            }
        }

        $this->assign('starer', $starer); // 已购课程
        return view('index/users');
    }

    /**
     * 退出登录
     */
    public function user_center_quit() {
        Cookie::set('still_login', null);
        session::clear();
        $this->success($msg = '已退出系统', $url = '/users/login', $data = '', $wait = 1);
        //$this->redirect('/users/login');
    }

    public function category($id)
    {
        // 从product表关联的course_list表中取出某课程的章节，如java课程的第一章、第一节、第二节
        $one = 0;
        $two = 0;
        $lists = new \app\admin\model\Product();
        $lists = $lists->find($id);
        if (!$lists) {
            $this->error('该课程不存在！');
        }
        if ($lists instanceof \app\admin\model\Product) {
            $listsArray = $lists->getCourseList();
        } else {
            $this->error('getCourseList方法执行错误!');
        }
        // 从course_video表中取出章节的具体视频等信息、如第一节的视频地址等
        $video_obj = new CourseVideo();
        $cataLogs = array();
        $watch_ids = '';
        foreach ($listsArray as $key => $list) {
            $videoId = $video_obj->where(array('menu_id'=>$list['id']))->find();
            $item['videoId'] = $videoId['video_path'];
            $item['menu_id'] = $videoId['menu_id'];
            $watch_ids .= $list['id'] . ',';
            if ($list['parent_id'] > 0) {
                $one = $one + 1;
            }
            $item['cLogId'] = $list['id'];
            $item['pid'] = $list['parent_id'];
            $list['parent_id'] ? $item['grade'] = 1 : $item['grade'] = 0;
            if ($item['grade'] == '0') {
                $outline = new CourseOutline();
                $outline = $outline->where('menu_id', $list['id'])->find();

                $item['outline'] = $outline ? $outline->outline : '暂无大纲';
            }
            $item['title'] = $list['title'];
            $item['content'] = $list['content'];
            $item['tLen'] = $list['time'] ? $list['time'] : '暂无时长信息';
            $item['watch_time'] = 0;
            $play_persent = 0;
            if (strpos($list['time'], ':') !== false) {
                $timesss = explode(':', $item['tLen']);
                $timeone = $timesss[0] * 3600;
                $timeotwo = $timesss[1] * 60;
                $time = $timeone + $timeotwo + $timesss[2] - 10;
                $uid = Session::get('user')['user_id'];
                $butime = db('video_time')->where('menu_id', $list['id'])->where('user_id', $uid)->find();
                if ($butime) {
                    if ($butime['sec'] >= $time) {
                        $numtime = '已学100%';
                        if ($list['parent_id'] > 0) {
                            $two = $two + 1;
                        }
                        $play_persent = $butime['sec'];
                    } else if ($butime['sec'] < $time) {
                        $nuim = $butime['sec'] / $time * 100;
                        $timdf = intval($nuim);
                        $numtime = '已学' . $timdf . '%';
                        $play_persent = $timdf;
                    }
                } else {
                    $numtime = '未开始';
                }
            } elseif ($item['tLen'] == '暂无时长信息') {
                $numtime = '未开始';
            } else {
                $numtime = $item['tLen'];
            }
            $item['play_persent'] = $play_persent;
            $item['time'] = $numtime;
            $cataLogs[] = $item;

        }

        $watch_ids = rtrim($watch_ids, ',');
        $studyPro['sTime'] = $one;
        $studyPro['pro'] = $two;
        $result['code'] = '1';
        $result['studyPro'] = $studyPro;
        $result['watch_ids'] = $watch_ids;
        $result['catalogs'] = $cataLogs;
        return $result;
    }
}